/*
 * EnigmaGM - A feature rich guild management system.
 * Copyright (C) 2007 ajiaojr.
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */
package org.ajiaojr.enigmagm.client.section;

import org.ajiaojr.enigmagm.client.data.Raid;
import org.ajiaojr.enigmagm.client.data.User;
import org.ajiaojr.enigmagm.client.data.viewer.ContentProvider;
import org.ajiaojr.enigmagm.client.data.viewer.TableContentProviderInput;
import org.ajiaojr.enigmagm.client.data.viewer.TableLabelProvider;
import org.ajiaojr.enigmagm.client.data.viewer.TableViewer;
import org.ajiaojr.enigmagm.client.service.RaidService;
import org.ajiaojr.enigmagm.client.service.UserService;
import org.ajiaojr.enigmagm.client.service.UserServiceAsync;
import org.ajiaojr.enigmagm.client.widget.PointSystemsListBox;
import org.ajiaojr.enigmagm.client.widget.RaidTableContentProviderInput;

import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.Frame;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

import java.util.List;

/**
 * @author ajiaojr
 */
public class AdministerSection extends Section {
  private static AdministerSection instance = new AdministerSection();

  public static AdministerSection getInstance() {
    return instance;
  }

  private DateTimeFormat dateTimeFormat =
      DateTimeFormat.getFormat("dd MMM yyyy HH:mm");

  private AdministerSection() {

    final HorizontalPanel mainPanel = new HorizontalPanel();
    initWidget(mainPanel);
    mainPanel.setWidth("100%");

    final VerticalPanel verticalPanel = new VerticalPanel();
    mainPanel.add(verticalPanel);
    mainPanel.setCellVerticalAlignment(verticalPanel,
        HasVerticalAlignment.ALIGN_TOP);
    verticalPanel.setWidth("100%");
    verticalPanel.setSpacing(6);

    Frame adFrame = new Frame(GWT.getModuleBaseURL() + "/ad.html");
    adFrame.setSize("200px", "350px");
    adFrame.setStyleName("adBox");

    mainPanel.add(adFrame);
    mainPanel.setCellVerticalAlignment(adFrame, HasVerticalAlignment.ALIGN_TOP);
    mainPanel.setCellHorizontalAlignment(adFrame,
        HasHorizontalAlignment.ALIGN_CENTER);
    mainPanel.setCellWidth(adFrame, "140px");

    final TabPanel tabPanel = new TabPanel();
    verticalPanel.add(tabPanel);
    tabPanel.setWidth("100%");

    addRaidsTab(tabPanel);

    final VerticalPanel verticalPanel_2 = new VerticalPanel();
    tabPanel.add(verticalPanel_2, "Characters");
    verticalPanel_2.setWidth("100%");

    addUsersTab(tabPanel);

    tabPanel.selectTab(0);
  }

  /*
   * (non-Javadoc)
   * 
   * @see org.ajiaojr.enigmagm.client.section.Section#getName()
   */
  public String getName() {
    return "Administer";
  }

  private void addRaidsTab(TabPanel tabPanel) {
    final VerticalPanel verticalPanel = new VerticalPanel();
    tabPanel.add(verticalPanel, "Raids");
    verticalPanel.setSpacing(5);
    verticalPanel.setWidth("100%");

    final HorizontalPanel horizontalPanel = new HorizontalPanel();
    verticalPanel.add(horizontalPanel);
    horizontalPanel.setSpacing(5);
    horizontalPanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);

    final Label pointSystemLabel = new Label("Point Systems");
    horizontalPanel.add(pointSystemLabel);

    final PointSystemsListBox pointSystemsListBox = new PointSystemsListBox();
    horizontalPanel.add(pointSystemsListBox);

    final TableViewer raidsViewer = new TableViewer();
    verticalPanel.add(raidsViewer.getWidget());

    ContentProvider raidsProvider = new ContentProvider() {

      public void inputChanged(Object input) {
        RaidTableContentProviderInput currentInput =
            (RaidTableContentProviderInput) input;

        RaidService.Util.getInstance().findByPointSystemID(
            currentInput.getPointSystemID(), currentInput.getFirstResult(),
            currentInput.getMaxResults(), new AsyncCallback() {
              public void onFailure(Throwable caught) {
                Window.alert(caught.getMessage());
              }

              public void onSuccess(Object result) {
                List raids = (List) result;
                contentListeners.fireContentChangedEvent(raids.toArray());
              }
            });

      }
    };

    raidsViewer.setContentProvider(raidsProvider);

    raidsViewer.addColumn("Instance Name", null);
    raidsViewer.addColumn("Raid Time", null);

    raidsViewer.setTableLabelProvider(new TableLabelProvider() {

      public String getLabel(Object object, int column) {
        Raid raid = (Raid) object;
        switch (column) {
          case 0:
            return raid.getRaidInstanceName();
          case 1:
            return dateTimeFormat.format(raid.getRaidTimeAsDate());
          default:
            return null;
        }
      }
    });

    pointSystemsListBox.addChangeListener(new ChangeListener() {
      public void onChange(Widget sender) {
        RaidTableContentProviderInput input =
            (RaidTableContentProviderInput) raidsViewer.getInput();
        int selectionIndex = pointSystemsListBox.getSelectedIndex();
        int value =
            Integer.parseInt(pointSystemsListBox.getValue(selectionIndex));
        if (value != input.getPointSystemID()) {
          input.setPointSystemID(value);
          raidsViewer.setInput(input);
        }
      }
    });

    raidsViewer.setInput(new RaidTableContentProviderInput(0, 0,
        TableViewer.DEFAULT_MAX_RESULTS, null));

    HorizontalPanel buttonsPanel = new HorizontalPanel();
    verticalPanel.add(buttonsPanel);

    buttonsPanel.setSpacing(5);

    Button addRaidButton = new Button("Add Raid");
    buttonsPanel.add(addRaidButton);
  }

  private void addUsersTab(TabPanel tabPanel) {
    final VerticalPanel verticalPanel = new VerticalPanel();
    tabPanel.add(verticalPanel, "Users");
    verticalPanel.setWidth("100%");

    final TableViewer usersViewer = new TableViewer();
    verticalPanel.add(usersViewer.getWidget());

    ContentProvider usersProvider = new ContentProvider() {

      public void inputChanged(Object input) {
        TableContentProviderInput currentInput =
            (TableContentProviderInput) input;
        UserServiceAsync userService = UserService.Util.getInstance();
        userService.list(currentInput.getFirstResult(), currentInput
            .getMaxResults(), new AsyncCallback() {

          public void onFailure(Throwable caught) {
            Window.alert(caught.getMessage());
          }

          public void onSuccess(Object result) {
            List users = (List) result;
            contentListeners.fireContentChangedEvent(users.toArray());
          }
        });
      }
    };

    usersViewer.setContentProvider(usersProvider);

    usersViewer.addColumn("User Name", null);

    usersViewer.setTableLabelProvider(new TableLabelProvider() {

      public String getLabel(Object object, int column) {
        User user = (User) object;
        switch (column) {
          case 0:
            return user.getUsername();

          default:
            return null;
        }
      }
    });

    usersViewer.setInput(new TableContentProviderInput(0,
        TableViewer.DEFAULT_MAX_RESULTS));
  }

}
